package com.rkhd.login;

import com.rkhd.application.ApplicationContext;

import com.rkhd.utils.HttpClientUtil;
import com.rkhd.xsy.MsgQueue;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.testng.annotations.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

public class ApplicatLogin {

    private static final String Log4jFile = "F:\\user\\Young\\workspace\\AutoMateInterface\\src\\conf\\log4j.properties";

    /**
     * 指定配置 log4j.properties文件信息的位置
     */
    static {

        Properties props = null;
        FileInputStream fis = null;
        try {
            // 从配置文件dbinfo.properties中读取配置信息
            props = new Properties();


            /**
             * main()  放入入口直接用 用相对路径就行
             */
//            fis = new FileInputStream( new File("src/conf/log4j.properties"));


            /**
             *  testng() 放入入口直接用 用相对或者绝对路径度行
             */
            fis = new FileInputStream(new File(Log4jFile));
            props.load(fis);
            PropertyConfigurator.configure(props);//装入log4j配置信息
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            fis = null;
        }


    }

    //    logEntryUrl 地址
    private static final String logEntryUrl = "https://crm-staging.xiaoshouyi.com/global/login-entry.action";
    //   do-login  Url地址
    private static final String apiUrl = ApplicationContext.getStaging_URL();
    // 封装 userid 和 EncryptionKey 的map
    Map<String, String> loginList = null;

    //加载日志记录器
    private static final Logger logger = Logger.getLogger(ApplicatLogin.class);

    private static final Map<String, Object> loginCommonMap = new HashMap<String, Object>();

    /**
     * @param //loginName 登录所需要的用户名
     * @param //password  登录所需要的密码
     * @return EncryptionKey
     */
    private Map<String, Object> getlogin() {

        MsgQueue msgQueue = MsgQueue.getMsgQueueInstance();
        HashMap<String, Object> queueStagingParameter = msgQueue.getStagingParameter();
        Map<String, Object> loginMap = getEncryptionKey(apiUrl, queueStagingParameter);

        return loginMap;

    }

    /**
     * @param loginMap 存放 tenantId  passport.id   encryptionKey  loginName的map 结合 ;
     */
//    @Test(dependsOnMethods = "ts")
    private void getLoginEntry(Map<String, Object> loginMap) {

        String doPost = HttpClientUtil.doPost(logEntryUrl, loginMap);

        JSONObject getLogEntryobj = JSONObject.fromObject(doPost);
        /**
         * 对 login_entry 结果进行断言
         */
        boolean assertResult = assertResult(getLogEntryobj);
        /**
         *   用总的 statusCode标记 接口是否响应成功 ;
         */
        int statusCode = assertResult(getLogEntryobj) ? 0 : 1;

        org.testng.Assert.assertTrue(statusCode == 0);
        logger.info(statusCode == 0 ? "loginSuccess" : "loginFail");

    }

    private boolean assertResult(JSONObject getLogEntryobj) {
        boolean flag = false;
        String STATUS_TEXT = "成功";
        String status = getLogEntryobj.getString("status");
        String statusText_resourceKey = getLogEntryobj.getString("statusText_resourceKey");
        String statusText = getLogEntryobj.getString("statusText");

        if (status != null && status.equals(String.valueOf(0)) &&
                "common.success".equals(statusText_resourceKey) && STATUS_TEXT.equals(statusText)) ;
        flag = true;
        return flag;


    }

    /**
     * @param apiUrl
     * @param queueStagingParameter
     * @return 返回封装  userId和 EncryptionKey 的 map组合
     */
    public static Map<String, Object> getEncryptionKey(String apiUrl, HashMap<String, Object> queueStagingParameter) {
        Map<String, Object> loginList = new HashMap<>();
        /**
         *   开启 SSL 认证   ;  忽略证书校验
         */
        String doLoginstr = HttpClientUtil.doPostSSL(apiUrl, queueStagingParameter);
        JSONObject doLoginObj = JSONObject.fromObject(doLoginstr);
        Iterator iterator = doLoginObj.keys();
        /**
         * 迭代外层循环 key
         */
        while (iterator.hasNext()) {
            String containKey = (String) iterator.next();
            if (containKey != null && "data".equals(containKey)) {
                JSONObject dataKey = (JSONObject) doLoginObj.get(containKey);
                //循环读取出 data:所包含的数据
                Iterator keys = dataKey.keys();
                while (keys.hasNext()) {
                    String next = (String) keys.next();

                    if ("userid".equals(next) && next != null) {
                        Object userid = dataKey.get("userid");
                        loginList.put("passport.id", userid);
                    }

                    if (next != null && "companyList".equals(next)) {
                        /**
                         * 解析的  id和 encryptionKey 必须在encryptionKeyJsonArray 数据中进行遍历查找
                         */
                        JSONArray encryptionKeyJsonArray = (JSONArray) dataKey.get(next);
                        for (int i = 0; i < encryptionKeyJsonArray.size(); i++) {

                            JSONObject tenantObj = encryptionKeyJsonArray.getJSONObject(i);
                            /**
                             *  以 id断言结果为主准,进行细粒度划分场景
                             */
                            if (tenantObj.get("id") != null && tenantObj.get("id").toString().equals(MsgQueue.getStagingTenantid())) {
                                /**
                                 * 取得 保持加密的秘钥encryptionKey
                                 */
                                String encryption = (String) tenantObj.get("encryptionKey");
                                /**
                                 *  存放到   HashMap结合中进行遍历操作
                                 */
                                loginList.put("encryptionKey", encryption);

                            }
                        }
                    }
                }
            }
        }
        return loginList;

    }

    @Test()
    public static void ts() {


        ApplicatLogin applicatLogin = new ApplicatLogin();
        // 登录分为两步骤 :  1. do-login

        Map<String, Object> loginMap = applicatLogin.getlogin();// do-login
//    2. login-entry
        /**
         *   tenantId :存放 租户 id
         *   loginName: 存放 loginName
         */
        loginMap.put("tenantId", MsgQueue.getStagingTenantid());
        loginMap.put("loginName", MsgQueue.getTenantName());
        applicatLogin.getLoginEntry(loginMap);
    }


    public static void main(String[] args) {

        ApplicatLogin applicatLogin = new ApplicatLogin();
        // 登录分为两步骤 :  1. do-login

        Map<String, Object> loginMap = applicatLogin.getlogin();// do-login
//    2. login-entry
        /**
         *   tenantId :存放 租户 id
         *   loginName: 存放 loginName
         */

        loginMap.put("tenantId", MsgQueue.getStagingTenantid());
        loginMap.put("loginName", MsgQueue.getTenantName());
        applicatLogin.getLoginEntry(loginMap);
    }




}